package com.global.college.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.global.college.R;
import com.global.college.UserData;
import com.global.college.api.ProgressSubscriber;
import com.global.college.api.RequestClient;
import com.global.college.base.BaseActivity;
import com.global.college.base.baselist.HsScrollViewPagerAdapter;
import com.global.college.data.net.TrainBannerBean;
import com.global.college.data.net.TrainDetailBean;
import com.global.college.data.net.VideoHistoryBean;
import com.global.college.ui.fragment.TrainDetailFragment;
import com.global.college.ui.fragment.home.NestedWebviewFragment;
import com.global.college.ui.fragment.training.TrainProblemFragment;
import com.global.college.utils.StringUtils;
import com.global.college.widget.tab.SlidingTabLayout;
import com.global.college.widget.tab.listener.OnTabSelectListener;
import com.gyf.barlibrary.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 已购买训练营详情
 *
 * @author: xjh
 * @datetime: 2021/12/6
 */
public class TrainDetailBoughtActivity extends BaseActivity {
    @BindView(R.id.mSlidingTab)
    SlidingTabLayout mSlidingTab;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tv_speed)
    TextView tvSpeed;
    @BindView(R.id.tv_study_day)
    TextView tvDay;
    @BindView(R.id.tv_study_time)
    TextView tvAllTime;
    @BindView(R.id.tv_study_average)
    TextView tvAverageTime;
    @BindView(R.id.iv_train_cover)
    ImageView ivCover;
    @BindView(R.id.btn_start_learn)
    TextView btnLearn;
    @BindView(R.id.tv_train_name)
    TextView tvTrainName;
    @BindView(R.id.tv_train_info)
    TextView tvTrainInfo;
    @BindView(R.id.tv_study_info)
    TextView tvStudyInfo;
    @BindView(R.id.tv_last_day)
    TextView tvLastDay;


    private List<Fragment> mFragments = new ArrayList<>();
    private List<String> mTitles = new ArrayList<>();
    private int currentPosition = 0;
    private String trainId;
    private String classId;

    /**
     * 不使用ImmersionBar 以满足沉浸式需求
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        useImmersionBar = false;
        setTheme(com.aliyun.vodplayer.R.style.NoActionTheme);
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_class_bought_train;
    }

    @Override
    public void onCreateNew(Bundle savedInstanceState) {
        setShowTitleBar(false);
//        hideSystembar();
        ImmersionBar.with(TrainDetailBoughtActivity.this)
                .statusBarColor(R.color.transparent)
                .statusBarDarkFont(true)
                .init();//.hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
        trainId = getIntent().getStringExtra("trainId");
        initTab();
        setListener();
        Log.i(TAG, "trainId:" + trainId);
    }

    private void setListener() {
        mSlidingTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
                currentPosition = position;
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initTab() {
        List<String> strs = new ArrayList<>();
        mTitles.add("学习路径");
//        mTitles.add("答疑");
        mTitles.add("岗位证书");
        for (int i = 0; i < mTitles.size(); i++) {
            strs.add(mTitles.get(i));
        }
        mFragments.add(TrainDetailFragment.newInstance(trainId, "1"));
//        mFragments.add(TrainProblemFragment.newInstance());
        mFragments.add(NestedWebviewFragment.newInstance("http://h5.uton.net/book"));

        HsScrollViewPagerAdapter adapter = new HsScrollViewPagerAdapter(getSupportFragmentManager(), mFragments, strs);
        viewPager.setAdapter(adapter);
        mSlidingTab.setTabSpaceEqual(false);
        mSlidingTab.setViewPager(viewPager);
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(currentPosition);
    }

    @Override
    public void getInitData() {
        getStudyBanner();
        getTrainDetail();
    }

    public void setDefaultClassId(String classId) {
        this.classId = classId;
        getVideoHistory(UserData.getInstance().getUserId(), trainId);
    }

    @OnClick({R.id.btn_start_learn, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                this.finish();
                break;
            case R.id.btn_start_learn:
                startActivity(new Intent(this, CourseDetailActivity.class)
                        .putExtra("classId", classId)
                        .putExtra("trainId", trainId));
                break;
            default:
                break;
        }
    }

    /**
     * 获取播放记录
     *
     * @param userId
     * @param trainId
     */
    public void getVideoHistory(String userId, String trainId) {
        RequestClient.getInstance().getVideoHistory(userId, trainId, null).subscribe(new ProgressSubscriber<VideoHistoryBean>(this, true) {
            @Override
            public void onNext(VideoHistoryBean model) {
                if (!StringUtils.isEmpty(model.getVideoId())) {
                    if (!StringUtils.isEmpty(model.getClassId())) {
                        classId = model.getClassId();
                    }
                    btnLearn.setText("继续学习");
                }
            }
        });
    }

    private void getStudyBanner() {
        RequestClient.getInstance().getTrainBanner(trainId, UserData.getInstance().getUserId()).subscribe(new ProgressSubscriber<TrainBannerBean>(this, false) {
            @Override
            public void onNext(TrainBannerBean model) {
                tvSpeed.setText(String.format("%.1f", (model.getStudySpeed() * 100)) + "%");
                tvDay.setText(model.getGrandDay() + "天");
                tvAllTime.setText(model.getStudyTime() / 60 + "分钟");
                tvAverageTime.setText(model.getStudyTimeDay() / 60 + "分钟");
                tvStudyInfo.setText(String.format("开始学习：%s    预计结束时间：%s", StringUtils.isEmpty(model.getStartTime()) ? "0" : (model.getStartTime()).split(" ")[0], StringUtils.isEmpty(model.getEndTime()) ? "0" : (model.getEndTime()).split(" ")[0]));
                tvLastDay.setText(model.getDayRemain() + "");
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }

    private void getTrainDetail() {
        RequestClient.getInstance().getTrainDetail(trainId, UserData.getInstance().getUserId()).subscribe(new ProgressSubscriber<TrainDetailBean>(this, false) {
            @Override
            public void onNext(TrainDetailBean model) {
                tvTrainName.setText(model.getName());
                tvTrainInfo.setText(String.format("已更新课程：%d门  |  课程时长：%d分钟", model.getClassNum(), model.getClassTimeCount()));
                Glide.with(TrainDetailBoughtActivity.this).load(model.getBackgroundUrl()).into(ivCover);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }
}
